import { Order, OrderService, OrderStatus } from "@mallfoundry/order"
import { PageList } from "@mallfoundry/shared/data"
import { useEffect, useState } from "react"

export function useOrder(orderId: string) {
  const [loading, setLoading] = useState(false)
  const [order, setOrder] = useState(new Order())

  useEffect(refresh, [orderId])

  function refresh() {
    setLoading(true)
    OrderService.getOrder(orderId)
      .then(setOrder)
      .finally(() => setLoading(false))
  }

  return {
    loading,
    refresh,
    order,
  }
}

interface UseOrdersOptions {
  page?: number | string
  limit?: number | string
  ids?: string | string[]
  storeId?: string
  statuses?: string | string[] | OrderStatus | OrderStatus[]
  placedTimeMin?: string
  placedTimeMax?: string
  timestamp?: string
}

export function useOrders(options: UseOrdersOptions) {
  const {
    page, limit,
    ids, storeId,
    statuses,
    placedTimeMin,
    placedTimeMax,
    timestamp,
  } = options
  const [loading, setLoading] = useState(false)
  const [pageOrders, setPageOrders] = useState(PageList.empty<Order>())

  function refresh() {
    setLoading(true)
    OrderService.getOrders(
      OrderService
        .createOrderQuery()
        .toBuilder()
        .page(page)
        .limit(limit)
        .storeId(storeId)
        .ids(ids)
        .statuses(statuses)
        .placedTimeMin(placedTimeMin)
        .placedTimeMax(placedTimeMax)
        .build(),
    )
      .then(setPageOrders)
      .finally(() => setLoading(false))
  }

  useEffect(refresh, [page, limit, storeId, ids, statuses, placedTimeMin, placedTimeMax, timestamp])

  return {
    loading,
    refresh,
    ...pageOrders,
  }
}
